package instance
{
	import flash.display.BitmapData;
	
	import view.BaseObject;

	public class GameObjectManager
	{
		//用于渲染画面的bitmapdata
		public var backBuffer:BitmapData;
		//用于清除backbuffer的画笔颜色
		private const clearColor:int = 0xff0000;
		
		//这一帧中新增的对象
		private var newGameObjects:Vector.<BaseObject> = new Vector.<BaseObject>();
		//这一帧中删除的对象
		private var removedGameObjects:Vector.<BaseObject> = new Vector.<BaseObject>();
		//当前活跃对象
		private var activeGameObjects:Vector.<BaseObject> = new Vector.<BaseObject>();
		
		public var lastFrame:Date;
		
		public function GameObjectManager(width:Number,height:Number) {
			backBuffer = new BitmapData(width,height);
			lastFrame = new Date();
		}
		
		public function enterFrame():void {
			
			var thisFrame:Date = new Date();
			var seconds:Number = (thisFrame.getTime() - lastFrame.getTime())/1000.0;
			lastFrame = thisFrame;
			
			for each (var gameObject:BaseObject in activeGameObjects)
				gameObject.enterFrame(seconds);
				
			updateActiveGameObjects();
//			trace(activeGameObjects.length);
			drawObjects();
		}
		
		public function drawObjects():void {
			
				backBuffer.fillRect(backBuffer.rect, clearColor);
				for each(var obj:BaseObject in activeGameObjects) {
					obj.copyToBackBuffer(backBuffer);
				}
		}
		
		public function addBaseObject(obj:BaseObject):void {
			newGameObjects.push(obj);
		}
		
		public function removeBaseObject(obj:BaseObject):void {
			removedGameObjects.push(obj);
		}
		
		public function updateActiveGameObjects():void {
			//add new game object
			for each(var newObj:BaseObject in newGameObjects) {
				activeGameObjects.push(newObj);
			}
			
			//remove old game object
			for each(var removedObj:BaseObject in removedGameObjects) {
				for(var i:int=0;i<activeGameObjects.length;i++) {
					if(removedObj === activeGameObjects[i]) {
						activeGameObjects.splice(i,1);
						activeGameObjects
						i--;
					}
				}
			}
			
			clearArr(newGameObjects);
			clearArr(removedGameObjects);
			
		}
		
		public function clearArr(arr:Vector.<BaseObject>):void {
			while(arr.length>0) {
				arr.shift();
			}
		}
		
	}
}